#pragma warning(disable:4996)
#include <iostream>
#include <WinSock2.h>
#include <string>
#pragma comment(lib,"ws2_32.lib")

//linux服务端的ip和端口
uint16_t serverport = 8080;
std::string serverip = "120.46.194.93";
const int num = 1024;


int main()
{
	//初始化
	WSAData wsd;
	if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
		std::cout << "WSAStartup error\n";
	else
		std::cout << "WSAStartup success\n";

	//创建套接字
	SOCKET sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sockfd == SOCKET_ERROR)
		std::cerr << "socket error\n";
	else
		std::cout << "socket success\n";

	//udp客户端不需要显示绑定

	//创建接收数据结构体sockarrd_in
	struct sockaddr_in server {};
	memset(&server, 0, sizeof(server));
	server.sin_family = AF_INET;
	server.sin_port = htons(serverport);
	server.sin_addr.s_addr = inet_addr(serverip.c_str());

	//接收数据
	std::string line;
	char buffer[num]{};
	while (true)
	{
		//向linux服务端发送消息
		std::cout << "please enter#";
		std::getline(std::cin, line);

		int n = sendto(sockfd, line.c_str(), (int)line.size(), 0, (struct sockaddr*)(&server), sizeof(server));
		if (n < 0)
		{
			std::cerr << "sendto error\n";
			break;
		}

		//接收来自linux返回的消息
		buffer[0] = 0;	//清空buffer中的数据
		struct sockaddr_in temp {};
		int len = sizeof(temp);
		n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)(&temp), &len);
		if (n < 0)
		{
			std::cerr << "recvfrom error\n";
			break;
		}
		else
		{
			buffer[n] = '\0';	//接收的数据
			std::cout << "Linux server 返回的数据是:" << buffer << std::endl;
		}
	}

	//关闭套接字
	closesocket(sockfd);

	//清理初始化
	WSACleanup();
	return 0;
}